<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <!-- 基础搜索条件，始终显示 -->
      <el-form-item label="计划编号">
        <el-input
          v-model="queryParams.planCode"
          placeholder="请输入计划编号/名称"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="计划状态">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.sc_plan_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <!-- 高级搜索条件，点击更多后显示 -->
      <template v-if="advancedSearch">
        <el-form-item label="计划开始时间">
          <el-date-picker
            v-model="queryParams.planStartTime"
            type="date"
            placeholder="请选择计划开始时间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="计划结束时间">
          <el-date-picker
            v-model="queryParams.planEndTime"
            type="date"
            placeholder="请选择计划结束时间"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="需求完成日期">
          <el-date-picker
            v-model="queryParams.requiredDate"
            type="date"
            placeholder="请选择需求完成日期"
            style="width: 240px"
          />
        </el-form-item>
      </template>

      <!-- 搜索按钮区域 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="text"
          size="mini"
          @click="toggleMoreSearch"
        >
          {{ advancedSearch ? '收起' : '更多' }}
          <i :class="[advancedSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down']"></i>
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sc:productionPlan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >编辑</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="planList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" width="70">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="计划编号" align="center" prop="planCode">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{ scope.row.planCode }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="计划名称" align="center" prop="planName" />
      <el-table-column label="工单数量" align="center" prop="workOrderCount" />
      <el-table-column label="来源类型" align="center" prop="sourceType" />
      <el-table-column label="成品名称" align="center" prop="productName" />
      <el-table-column label="成品编号" align="center" prop="productCode" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="计划数量" align="center" prop="plannedQty" />
      <el-table-column label="计划开工时间" align="center" prop="planStartTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划完工时间" align="center" prop="planEndTime" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="需求日期" align="center" prop="requiredDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.requiredDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sc_plan_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="scope.row.status !== '已完成' && scope.row.status !== '已关闭' && scope.row.status !== '已撤回'"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="scope.row.status === '未分解'"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDecompose(scope.row)"
            v-if="scope.row.status !== '1' && scope.row.status !== 1"
          >分解</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="handleRollback(scope.row)"
            v-if="scope.row.status === '已分解' || scope.row.status === '已关闭'"
          >撤回</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listPlan, decomposePlan, delProductionPlan } from "@/api/sc/plan";
import DictTag from "@/components/DictTag"

export default {
  name: "ScPlan",
  components: {
    DictTag
  },
  dicts: ['sc_order_source', 'sc_plan_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的计划编码
      planCodes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划表格数据
      planList: [],
      // 状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planCode: undefined,
        planName: undefined,
        status: undefined,
        planStartTime: undefined,
        planEndTime: undefined,
        requiredDate: undefined
      },
      // 控制搜索条件的展开/收起
      advancedSearch: false
    };
  },
  created() {
    this.getList();
  },
  watch: {
    // 监听路由变化，页面重新加载时刷新数据
    '$route'(to) {
      if (to.path === '/sc/plan' || to.name === 'ScPlan') {
        console.log('生产计划页面路由变化，刷新数据');
        this.getList();
      }
    },
    // 监听查询参数变化
    queryParams: {
      handler(newVal, oldVal) {
        if (oldVal && JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('生产计划查询参数变化，刷新数据');
          this.getList();
        }
      },
      deep: true
    }
  },
  methods: {
    /** 查询生产计划列表 */
    getList() {
      this.loading = true;
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 日期格式化
    parseTime(time, pattern) {
      if (time == null || time === '') {
        return "";
      }
      const format = pattern || '{y}-{m}-{d}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        if (result.length > 0 && value < 10) {
          value = '0' + value;
        }
        return value || 0;
      });
      return time_str;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        planCode: undefined,
        planName: undefined,
        status: undefined,
        planStartTime: undefined,
        planEndTime: undefined,
        requiredDate: undefined
      };
      this.handleQuery();
    },
    /** 切换更多搜索条件 */
    toggleMoreSearch() {
      // 控制搜索条件的展开/收起
      this.advancedSearch = !this.advancedSearch;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productionPlanId);
      this.planCodes = selection.map(item => item.planCode);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/sc/plan/add' });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const planCode = row.planCode || this.planCodes[0];
      this.$router.push({ path: '/sc/plan/edit', query: { planCode: planCode } });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.productionPlanId ? [row.productionPlanId] : this.ids;
      const displayCodes = row.planCode || this.planCodes;
      this.$modal.confirm('是否确认删除生产计划编号为"' + displayCodes + '"的数据项？').then(function() {
        return delProductionPlan(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 分解按钮操作 */
    handleDecompose(row) {
      const planCode = row.planCode;
      const confirmMessage = "确定要分解当前计划吗？系统将根据对应的BOM，分解为多个工单。";
      this.$modal.confirm(confirmMessage).then(() => {
        this.loading = true;
        return decomposePlan(planCode);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("分解成功");
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      const planCode = row.planCode;
      this.$router.push({ path: '/sc/plan/detail', query: { planCode: planCode } });
    },
    /** 撤回按钮操作 */
    handleRollback(row) {
      const planCode = row.planCode;
      this.$modal.confirm('是否确认撤回生产计划编号为"' + planCode + '"的数据项？').then(() => {
        // 模拟撤回操作
        this.$modal.msgSuccess("撤回成功");
        this.getList();

        // 实际项目中应该调用API，暂时注释避免404错误
        // return rollbackProductionPlan(planCode);
      }).then(() => {
        // this.$modal.msgSuccess("撤回成功");
        // this.getList();
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.el-table .cell {
  white-space: nowrap;
}
</style>
